package com.hzbank.juc.pattern;

import lombok.extern.slf4j.Slf4j;

import java.util.Hashtable;
import java.util.Map;
import java.util.Set;

/**
 * @description:
 * @author: libugu@cskaoyan.com
 * @date 2023/12/22 - 15:50
 */
@Slf4j
public class Mailboxs {

    private static Map<Integer,GuardedObject2> boxs = new Hashtable();
    private static int id = 1;
    public static synchronized int generateId(){
        return id++;
    }

    public static GuardedObject2 getGuarded(int id){
        return boxs.remove(id);
    }

    public static GuardedObject2 create(){
        GuardedObject2 go = new GuardedObject2(generateId());
        boxs.put(go.getId(),go);
        return go;
    }
    public static Set<Integer> getIds(){

        return boxs.keySet();
    }

}

@Slf4j
class People extends Thread{

    @Override
    public void run() {
        // 收信
        GuardedObject2 guardedObject = Mailboxs.create();
        log.debug("开始收信 id:{}", guardedObject.getId());
        Object mail = guardedObject.get(5000);
        log.debug("收到信 id:{}, 内容:{}", guardedObject.getId(), mail);
    }
}
@Slf4j
class Postman extends Thread {
    private int id;
    private String mail;
    public Postman(int id, String mail) {
        this.id = id;
        this.mail = mail;
    }
    @Override
    public void run() {
        GuardedObject2 guardedObject = Mailboxs.getGuarded(id);
        log.debug("送信 id:{}, 内容:{}", id, mail);
        guardedObject.complete(mail);
    }
}
